<?php
// $Id$

/**
 * Controller_Sec 控制器
 */
class Controller_Sec extends Controller_Abstract
{

	/**
	 * 查看最好的几个证券
	 * 
	 */
	function actionIndex()
	{
		$cnt = 10; //显示的条目
        // 为 $this->_view 指定的值将会传递数据到视图中
		$this->_view['location'] = "sec";
		
		
		$sql = "select sec.id, name, code, sec_sum.follow_cnt, view_cnt, press_cnt,
				(10 * sec_sum.follow_cnt) + view_cnt + press_cnt as score
			from sec_sum, sec
			where sec_sum.id = sec.id
			order by score desc
			limit 10";
		$res = DB::query($sql);
		
		$secs = array();
		while($row = $res->fetch_assoc()){
			if($row['score'] == 0){
				break;
			}
			$secs[] = $row;
		}
		
		$this->_view['secs'] = $secs;
	}
	
	
	function actionP(){
		$this->_view['location'] = "sec";
		
		if (QValidator::validate_is_digits($_GET['id'])){
			$id = intval($_GET['id']);
			
			//sec info
			$sql = "select name, sec_sum.follow_cnt, press_cnt, view_cnt, code, sec.id
				from sec, sec_sum
				where sec.id = $id and sec_sum.id = $id";
			$res = DB::query($sql);
			if($row = $res->fetch_assoc()){
				$this->_view['sec'] = $row;
			}
			
			//if sec followed
			if(in_array("member", Q::registry('app')->currentUserRoles())){
				$user = Q::registry("app")->currentUser();
				$uid = $user['id'];
				$sql = "select * from sec_follow
					where user_id = $uid and sec_id = $id";
				$res = DB::query($sql);
				if($row = $res->fetch_assoc()){
					$this->_view['follow'] = true;
				}else{
					$this->_view['follow'] = false;
				}
			}
			
			
			//sec press
			$sql = "select user.name as username, nickname, title, press, press_time, sec_press.id
				from sec_press_relation, sec_press, user
				where sec_press_relation.sec_id = $id and
					press_id = sec_press.id and 
					user.id = sec_press.user_id";
			$res = DB::query($sql);
			$ps = array();
			while($row = $res->fetch_assoc()){
				if (!empty($row['title'])){
					$row['press'] = $row['title'];
				}else{
					if (iconv_strlen($row['press'], 'utf-8') > 80 ){
						$row['press'] = iconv_substr($row['press'], 0, 80, "utf-8") . "... ...";
					}
				}
				$ps[] = $row;
			}
			
			$this->_view['ps'] = $ps;
			
			//display sec views
		}else{
			return $this->_redirect(url("sec"));
		}
	}
	
	/**
	 * 发表评论
	 *
	 */
	function actionIssue(){
		//处理的参数： type, id, content
		
		//如果没有的登录，提示登录
		if(!in_array("member", Q::registry('app')->currentUserRoles())){
			return "{state: 'fail', data : '您还未登录，请先登录'}";
		}else{
			$user = Q::registry("app")->currentUser();
		}
		
		//如果某个参数不正确，那么返回错误state: fail
		//如果type参数不正确，返回参数错误
		$errJson = "{state: 'fail', data : '参数错误'}";
		if(!isset($_POST['type']) || ($_POST['type'] != '-1'
			&& $_POST['type'] != '0' && $_POST['type'] != '1')){
            $type = isset($_POST['type']) ? $_POST['type'] : "not set";
			return "{state: 'fail', data : '参数错误, type=$type'}";
		}else{
			$type = $_POST['type'];
		}
		
		if(!isset($_POST['id']) || intval($_POST['id']) != $_POST['id']){
			return $errJson;
		}else{
			$id = intval($_POST['id']);
		}
		
		$content = trim(preg_replace("/　/", " ", $_POST['content']));
		if (strlen($content) == 0){
			return "{state: 'fail', data : '评论要言之有物'}";
		}
		//content大于某个数量了怎么办？
		else if (strlen($content) > 65530){
			$content = iconv_substr($content, 0, 20000, 'UTF-8');
		}
		$content = DB::real_escape($content);
		
		DB::beginTransaction();
		
        $comment_time = date("Y-m-d H:i:s", time());
		$query = "insert into sec_comment
			set comment = '$content', vote = '$type',
			comment_time = '$comment_time', sec_id = '$id', 
			user_id = '{$user['id']}'";	
		DB::query($query);

		$insert_id = DB::insert_id();
		
		if ($type == '-1'){
			$up_cnt = $comment_cnt = 0;
			$down_cnt = 1;
			$update = 'down_cnt = down_cnt + 1';
		}else if($type == '0'){
			$up_cnt = $down_cnt = 0;
			$comment_cnt = 1;
			$update = 'comment_cnt = comment_cnt + 1';
		}else{
			$down_cnt = $comment_cnt = 0;
			$up_cnt = 1;
			$update = 'up_cnt = up_cnt + 1';
		}
		$date = $this->today();
		$query = "insert into sec_comment_sum ( up_cnt, down_cnt, comment_cnt, date, sec_id, comment_id, last_comment_time)
			 values( $up_cnt, $down_cnt, $comment_cnt, '$date' , $id, $insert_id, '$comment_time') 
			 ON DUPLICATE KEY 
			 update $update;";
		DB::query($query);
		DB::commit();

		return "{state : 'success'}";
	}
	
	/**
	 * 用户关注某个证券
	 *
	 * @return mixed
	 */
	function actionFavor(){
		
		//如果没有的登录，转到登录页面
		if(!in_array("member", Q::registry('app')->currentUserRoles())){
			return "{state: 'fail', data : '您还未登录，请先登录'}";
		}else{
			$user = Q::registry("app")->currentUser();
		}
		
		if(isset($_POST['id']) && intval($_POST['id']) == $_POST['id']){
			$id = intval($_POST['id']);
		}else{
			return "{'state' : 'fail', 'data': '参数错误'}";
		}

		try{
			$query = "select * from sec_follow where user_id = {$user['id']}  and sec_id = $id";
			$res = DB::query($query);
			if(DB::num_rows() > 0){
				return "{'state': 'success'}";
			}
			DB::beginTransaction();
			$query = "insert into sec_follow set user_id = {$user['id']} , sec_id = $id, follow_time=now()";
			DB::query($query);
			$query = "update sec_sum set follow_cnt = follow_cnt + 1 where id = $id";
			DB::query($query);
			DB::commit();
		}catch(Exception $e){
			return "{'state': 'fail', 'date': '$e'}";
		}
		
		return "{'state' : 'success'}";
		
	}
	
	
	/**
	 * 用户取消关注某个证券
	 *
	 * @return mixed
	 */
	function actionUnfavor(){
		//如果没有的登录，转到登录页面
		if(!in_array("member", Q::registry('app')->currentUserRoles())){
			return "{state: 'fail', data : '您还未登录，请先登录'}";
		}else{
			$user = Q::registry("app")->currentUser();
		}
		
		if(isset($_POST['id']) && intval($_POST['id']) == $_POST['id']){
			$id = intval($_POST['id']);
		}else{
			return "{'state' : 'fail', 'data': '参数错误'}";
		}
		
		//先检查是不是在关注，如果是在关注，那么执行删除命令，否则直接返回。
		$query = "select * from sec_follow where user_id = {$user['id']} and sec_id = $id";
		try{
			DB::query($query);
			if(DB::num_rows() == 0){
				return "{'state': 'success'}";
			}
			DB::beginTransaction();
			$query = "delete from sec_follow where user_id = {$user['id']} and sec_id = $id";
			DB::query($query);
			$query = "update sec_sum set follow_cnt = follow_cnt - 1 where id = $id and follow_cnt > 0";
			DB::query($query);
			DB::commit();
		}catch(Exception $e){
			return "{'state':'fail', 'date': '$e'}";
		}
		
		return "{'state': 'success'}";
	}
	
	
	/**
	 * 查看某个证券的评论
	 * 
	 */
	function actionComment(){
		$this->_view['location'] = "sec";
		$this->_view['cssfiles'] = array('small');
			
		$commentPerPage = 36;
		//查看评论
		if(isset($_GET['id']) && QValidator::validate_is_int($_GET['id'])){
			$id = intval($_GET['id']);
		}else{
			return $this->_redirect("/");
		}
		$time = false;
		$today = true;
		$yesterday = "";
		$tomorrow = "";
		
		if(isset($_GET['date'])){
			$time = strtotime($_GET['date']);
		}
		
		if($time == false){
			$date = $this->today();
			$time = strtotime($date);
			$dateFrom = date("Y-m-d", $time - $this->cycleLen + 24 * 3600);
			$dateTo = $date;
			$title = "最近7天内的评论";
		}else{
			$date = date("Y-m-d", $time);
			$dateFrom = date("Y-m-d", $time - $this->cycleLen + 24 * 3600);
			$dateTo = $date;
			$title = "{$dateFrom}到{$dateTo}的评论";
			$today = false;
		}
		
		$yesterday = $this->lastCycle($date);
		$tomorrow = $this->nextCycle($date);
		
		$this->_view['id'] = $id;
		//$this->_view['date'] = date("Y-m-d（星期N）", $time);
		$this->_view['dateFrom'] = $dateFrom;
		$this->_view['dateTo'] = $dateTo;
		$this->_view['yesterday'] = $yesterday;
		if($time < strtotime($this->today())){
			$this->_view['tomorrow'] = $tomorrow;
		}
		$this->_view['today'] = $today;
		$this->_view['page'] = 1;
		$this->_view['lastPage'] = 1;
		
		$fromto = $this->cycleFromTo($time);
		$fromto['from'] = date("Y-m-d H:i:s", $fromto['from']);
		$fromto['to'] = date("Y-m-d H:i:s", $fromto['to']);
		$query = "select id, name, code, type, follow_cnt from sec where id = $id";
		$res = DB::query($query);
		if(DB::num_rows() < 1){
			return $this->_redirect("/");
		}else{
			$row = $res->fetch_assoc();
			$title = $row['name'] . $title;
			$this->_view['title'] = $title;
			
			//如果当前用户没有登录，那么关注部分就会显示“关注”，而不是“取消关注”
			if(in_array("member", Q::registry('app')->currentUserRoles())){
				$user = Q::registry("app")->currentUser();
				$user_id = $user['id'];
				$query = "select count(*) as follow from sec_follow where user_id = $user_id and sec_id = $id";
				$follow = DB::query($query)->fetch_assoc();
				$row = array_merge($row, $follow);
			}
			
			$query = "select sum(up_cnt) as upCnt, sum(down_cnt) as downCnt, 
				 sum(comment_cnt) as commentCnt
				 from sec_comment_sum
				 where sec_id = $id and 
				 sec_comment_sum.date < '{$fromto['to']}' and 
				 sec_comment_sum.date >= '{$fromto['from']}' ";
			$res = DB::query($query);
			//如果没有相关评论(sec_comment_sum中没有记录），那么按照0来计算，sec_comment中的评论也不读取了
			if (DB::num_rows() < 1){
				$query = "select (count(*)+1) as sec_order 
					from sec_comment_sum
					where date = '$date' and 
							(up_cnt - down_cnt) > 0";
				$res = DB::query($query);
				$row = array_merge($row, $res->fetch_assoc());
				$this->_view['row'] = array_merge($row, array(
					"upCnt" => 0,
					"downCnt" => 0,
					"allCnt" => 0,
					'score' => 0,
				));
			}else{
			//sec_comment_sum中有记录，那么读取，然后读取相应的sec_comment中的评论
				$row = array_merge($row, $res->fetch_assoc());
				$row['upCnt'] = intval($row['upCnt']);
				$row['downCnt'] = intval($row['downCnt']);
				$row['allCnt'] = $row['upCnt'] + $row['downCnt'] + $row['commentCnt'];
				$row['score'] = $row['upCnt'] - $row['downCnt'];
				//计算排名
				$query = "select (count(*)+1) as sec_order
					from (
						select sum(up_cnt) as upCnt, sum(down_cnt) as downCnt, 
							sec_id
						from sec_comment_sum
						where date < '{$fromto['to']}' and 
						  date >= '{$fromto['from']}'
						group by sec_id) as cycleSum
					where (upCnt - downCnt) > {$row['score']}";
				$res = DB::query($query);
                $row = array_merge($row, $res->fetch_assoc());
                
                if($row['score'] < 0){
                	$query = "select count(*) as sec_cnt
                			from sec";
                	$cnt = DB::query($query)->fetch_assoc();
                	$sec_cnt = $cnt['sec_cnt'];
                	
                	$query = "select count(*) as sum_cnt
                		from sec_comment_sum";
                	$cnt = DB::query($query)->fetch_assoc();
                	$sum_cnt = $cnt['sum_cnt'];
                	
                	$row['sec_order'] = $row['sec_order'] + $sec_cnt - $sum_cnt;
                }
				$this->_view['row'] = $row;
				
				//查看评论
				$comments = array();
				$query = "select nickname, name as username, comment_time, comment, vote
						from sec_comment, user
						where sec_id = $id and comment_time between '{$fromto['from']}' and '{$fromto['to']}' 
								and sec_comment.user_id = user.id
						order by comment_time asc";
				$res = DB::query($query);
				//QLog::log("find comment query: $query", QLog::DEBUG);
				while($com = $res->fetch_assoc()){
					$comments[] = $com;
				}
				$this->_view['comments'] = $comments;
			}
			
		}
	}
}


